package com.dragon.web.commons.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dragon.app.commons.dto.BankcardSaveDTO;
import com.dragon.loan.entity.CmAttachment;
import com.dragon.loan.service.CmAttachmentIDragonService;
import com.dragon.loan.service.LoanInfoIDragonService;
import com.dragon.web.commons.constant.Constant;
import com.dragon.web.commons.constant.ErrorCode;
import com.dragon.web.commons.filter.CorsFilter;
import com.dragon.web.commons.utils.FileUtils;
import com.dragon.web.commons.utils.ImageUtils;
import com.dragon.web.commons.utils.UserUtils;
import com.dragon.web.commons.vo.FintechResult;
import com.fintech.common.enums.ReturnCode;
import com.fintech.third.model.ocr.IdCardDto;
import com.fintech.third.service.ocr.CardOcrService;
import com.fintech.user.entity.RealNameAuthentication;
import com.fintech.user.entity.User;
import com.fintech.user.service.RealNameAuthenticationService;
import com.marvels.common.utils.MarvelsLogUtil;

import cn.hutool.core.bean.BeanUtil;


@Controller
@RequestMapping("${platform.name.code}/file")
public class FileController {

	@Autowired
	private CmAttachmentIDragonService cmAttachmentIDragonService;
	@Autowired
	private RealNameAuthenticationService realNameAuthenticationService;
	@Autowired
	private LoanInfoIDragonService loanInfoIDragonService;
	@Autowired
	private CardOcrService cardOcrService;

	@Value("${marvels.file.upload.basepath}")
	private String nfsFileSystem;

	@ResponseBody
	@RequestMapping(value = "/upload/ic")
	public FintechResult upload(MultipartFile file ,HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			 MarvelsLogUtil.getInstance().info(CorsFilter.threadLocalUUID.get() + "------------------------上传 -------  file = " + file);
			// 限制文件的类型，文件的大小 TODO
			String prefix = FileUtils.getPathPrefix();
			String uuid = UUID.randomUUID().toString();
			String path = nfsFileSystem + prefix;
			String fileName = "idCard_" + uuid;
			String smallFileName = "idCard_samll_" + uuid;
			try {
				String temStr = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
				fileName = fileName + temStr;
				smallFileName = smallFileName + temStr;
			} catch (Exception e1) {
				fileName = fileName + ".png";
				smallFileName = smallFileName + ".png";
			}
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// springboot 是用这种方式会存在上传问题
			String orgImageFilePath = path + File.separator + fileName;
			File tempFile = new File(orgImageFilePath);
			org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);

			//对身份证进行ocr
			IdCardDto idCardDto = cardOcrService.idCardOcr(tempFile);
			if(null != idCardDto) {
				Map<String,Object> beanMap = BeanUtil.beanToMap(idCardDto);
				resultMap.putAll(beanMap);
			}

			// 保存缩咯图
			String smallImageFilePaht = path + File.separator + smallFileName;
			ImageUtils.thumbnailImage(tempFile, smallImageFilePaht);

			String imageReviewPath =  Constant.IMAGE_REVIEW_PERFIX+prefix+ File.separator+fileName;
			String imageSmallReviewPath = Constant.IMAGE_REVIEW_PERFIX+prefix+ File.separator+smallFileName;
			resultMap.put("smallPath", imageSmallReviewPath);
			resultMap.put("path",imageReviewPath);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(CorsFilter.threadLocalUUID.get() + "------------------------上传 -------  file = " + file, e);
			return FintechResult.getResult(ErrorCode.FAIL, "上传失败", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", resultMap);
	}

	@ResponseBody
	@RequestMapping(value = "/upload/otherImages")
	public FintechResult uploadOtherImages(MultipartFile[] identityImgFiles ,MultipartFile[] creditImgFiles ,MultipartFile[] tradeImgFiles ,MultipartFile[] objectImgFiles ,HttpServletRequest request,@RequestHeader String accessToken, @RequestHeader String idFintechUmUser) {
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			MarvelsLogUtil.getInstance().info(CorsFilter.threadLocalUUID.get() + "------------------------上传 -------uploadOtherImages ----------");
			// 限制文件的类型，文件的大小 TODO
			String prefix = FileUtils.getPathPrefix();
			String path = nfsFileSystem + prefix;
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 其他身份证明材料
			StringBuilder identityImages = new StringBuilder();
			StringBuilder smallIdentityImages = new StringBuilder();
			for(MultipartFile file : identityImgFiles)
			{
				String uuid = UUID.randomUUID().toString();
				String fileName = "identity_" + uuid;
				String smallFileName = "identity_samll_" + uuid;
				try {
					String temStr = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
					fileName = fileName + temStr;
					smallFileName = smallFileName + temStr;
				} catch (Exception e1) {
					fileName = fileName + ".png";
					smallFileName = smallFileName + ".png";
				}
				String orgImageFilePath = path + File.separator + fileName;
				File tempFile = new File(orgImageFilePath);
				org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);

				// 保存缩咯图
				String smallImageFilePaht = path + File.separator + smallFileName;
				ImageUtils.thumbnailImage(tempFile, smallImageFilePaht);

				String imageReviewPath =  Constant.IMAGE_REVIEW_PERFIX+prefix+ File.separator+fileName;
				String imageSmallReviewPath = Constant.IMAGE_REVIEW_PERFIX+prefix+ File.separator+smallFileName;
				identityImages.append(imageReviewPath).append(";");
				smallIdentityImages.append(imageSmallReviewPath).append(";");
			}
			resultMap.put("identityImages",identityImages.indexOf(";")>-1?identityImages.deleteCharAt(identityImages.lastIndexOf(";")):identityImages);
			resultMap.put("smallIdentityImages",smallIdentityImages.indexOf(";")>-1?smallIdentityImages.deleteCharAt(smallIdentityImages.lastIndexOf(";")):smallIdentityImages);

			// 征信图片
			// 其他身份证明材料
			StringBuilder creditImages = new StringBuilder();
			StringBuilder smallCreditImages = new StringBuilder();
			for(MultipartFile file : creditImgFiles)
			{
				String uuid = UUID.randomUUID().toString();
				String fileName = "credit_" + uuid;
				String smallFileName = "credit_samll_" + uuid;
				try {
					String temStr = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
					fileName = fileName + temStr;
					smallFileName = smallFileName + temStr;
				} catch (Exception e1) {
					fileName = fileName + ".png";
					smallFileName = smallFileName + ".png";
				}
				String orgImageFilePath = path + File.separator + fileName;
				File tempFile = new File(orgImageFilePath);
				org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);

				// 保存缩咯图
				String smallImageFilePaht = path + File.separator + smallFileName;
				ImageUtils.thumbnailImage(tempFile, smallImageFilePaht);

				String imageReviewPath =  Constant.IMAGE_REVIEW_PERFIX+prefix+ File.separator+fileName;
				String imageSmallReviewPath = Constant.IMAGE_REVIEW_PERFIX+prefix+ File.separator+smallFileName;
				creditImages.append(imageReviewPath).append(";");
				smallCreditImages.append(imageSmallReviewPath).append(";");
			}
			resultMap.put("creditImages",creditImages.indexOf(";")>-1?creditImages.deleteCharAt(creditImages.lastIndexOf(";")):creditImages);
			resultMap.put("smallCreditImages",smallCreditImages.indexOf(";")>-1?smallCreditImages.deleteCharAt(smallCreditImages.lastIndexOf(";")):smallCreditImages);

			// 交易图片
			StringBuilder tradeImages = new StringBuilder();
			StringBuilder smallTradeImages = new StringBuilder();
			for(MultipartFile file : tradeImgFiles)
			{
				String uuid = UUID.randomUUID().toString();
				String fileName = "trade_" + uuid;
				String smallFileName = "trade_samll_" + uuid;
				try {
					String temStr = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
					fileName = fileName + temStr;
					smallFileName = smallFileName + temStr;
				} catch (Exception e1) {
					fileName = fileName + ".png";
					smallFileName = smallFileName + ".png";
				}
				String orgImageFilePath = path + File.separator + fileName;
				File tempFile = new File(orgImageFilePath);
				org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);

				// 保存缩咯图
				String smallImageFilePaht = path + File.separator + smallFileName;
				ImageUtils.thumbnailImage(tempFile, smallImageFilePaht);

				String imageReviewPath =  Constant.IMAGE_REVIEW_PERFIX+prefix+ File.separator+fileName;
				String imageSmallReviewPath = Constant.IMAGE_REVIEW_PERFIX+prefix+ File.separator+smallFileName;
				tradeImages.append(imageReviewPath).append(";");
				smallTradeImages.append(imageSmallReviewPath).append(";");
			}
			resultMap.put("tradeImages",tradeImages.indexOf(";")>-1?tradeImages.deleteCharAt(tradeImages.lastIndexOf(";")):tradeImages);
				resultMap.put("smallTradeImages",smallTradeImages.indexOf(";")>-1?smallTradeImages.deleteCharAt(smallTradeImages.lastIndexOf(";")):smallTradeImages);

			// 实物图片

			StringBuilder objectImages = new StringBuilder();
			StringBuilder smallObjectImages = new StringBuilder();
			for(MultipartFile file : objectImgFiles)
			{
				String uuid = UUID.randomUUID().toString();
				String fileName = "object_" + uuid;
				String smallFileName = "object_samll_" + uuid;
				try {
					String temStr = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
					fileName = fileName + temStr;
					smallFileName = smallFileName + temStr;
				} catch (Exception e1) {
					fileName = fileName + ".png";
					smallFileName = smallFileName + ".png";
				}
				String orgImageFilePath = path + File.separator + fileName;
				File tempFile = new File(orgImageFilePath);
				org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);

				// 保存缩咯图
				String smallImageFilePaht = path + File.separator + smallFileName;
				ImageUtils.thumbnailImage(tempFile, smallImageFilePaht);

				String imageReviewPath =  Constant.IMAGE_REVIEW_PERFIX+prefix+ File.separator+fileName;
				String imageSmallReviewPath = Constant.IMAGE_REVIEW_PERFIX+prefix+ File.separator+smallFileName;
				objectImages.append(imageReviewPath).append(";");
				smallObjectImages.append(imageSmallReviewPath).append(";");
			}
			resultMap.put("objectImages",objectImages.indexOf(";")>-1?objectImages.deleteCharAt(objectImages.lastIndexOf(";")):objectImages);
			resultMap.put("smallObjectImages",smallObjectImages.indexOf(";")>-1?smallObjectImages.deleteCharAt(smallObjectImages.lastIndexOf(";")):smallObjectImages);


		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(CorsFilter.threadLocalUUID.get() + "------------------------上传 -------uploadOtherImages ", e);
			return FintechResult.getResult(ErrorCode.FAIL, "上传失败", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", resultMap);
	}

	@ResponseBody
	@RequestMapping(value = "/upload/custSignImage")
	public FintechResult uploadCustSignImage(MultipartFile file ,HttpServletRequest request,@RequestHeader String accessToken, @RequestHeader String idFintechUmUser) {
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			 MarvelsLogUtil.getInstance().info(CorsFilter.threadLocalUUID.get() + "------------------------上传 -------uploadCustSignImage  file = " + file);
			// 限制文件的类型，文件的大小 TODO
			String prefix = FileUtils.getPathPrefix();
			String uuid = UUID.randomUUID().toString();
			String path = nfsFileSystem + prefix;
			String fileName = "sign_" + uuid;
			try {
				String temStr = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
				fileName = fileName + temStr;
			} catch (Exception e1) {
				fileName = fileName + ".png";
			}
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			String orgImageFilePath = path + File.separator + fileName;
			File tempFile = new File(orgImageFilePath);
			org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);

			String imageReviewPath =  Constant.IMAGE_REVIEW_PERFIX+prefix+ File.separator+fileName;

			//1 验证是否实名认证
//			RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(user.getId());
//			if (null == realNameAuthentication) {
//				return FintechResult.getResult(ErrorCode.NO_VERIFY, "", null);
//			}
//
//			//2 获取当前贷款申请编号
//			String loanId = loanInfoIDragonService.selectCustApplyingLoanId(realNameAuthentication.getIdentityCardNo());
//
//			CmAttachment cmAttachment = new CmAttachment();
//			cmAttachment.setLoanId(loanId);
//			cmAttachment.setAtmtType("SIGN_IMAGE");
//			cmAttachment.setFileName(fileName);
//			cmAttachment.setFileLocation(imageReviewPath);
//			cmAttachmentIDragonService.insertMsg(cmAttachment);

			resultMap.put("path",imageReviewPath);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(CorsFilter.threadLocalUUID.get() + "------------------------上传 -------uploadCustSignImage  file = " + file, e);
			return FintechResult.getResult(ErrorCode.FAIL, "上传失败", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", resultMap);
	}

	@ResponseBody
	@RequestMapping(value = "/upload/bankOcr")
	public FintechResult bankCradOcr(MultipartFile file ,HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			if(null == file || null == file.getBytes() || file.getBytes().length==0) {
				FintechResult.getResult(ErrorCode.FAIL, "银行卡图片不存在", resultMap);
			}

			byte[] fileBytes = file.getBytes();
			//对身份证进行ocr
			BankcardSaveDTO bankCardDto = cardOcrService.bankCardOcr(ImageUtils.imageToBase64(fileBytes));
			if(null == bankCardDto || StringUtils.isBlank(bankCardDto.getBankCardNum())) {
				return FintechResult.getResult(ErrorCode.FAIL, "银行卡识别失败", null);
			}

			resultMap.put("bankCardNo", bankCardDto.getBankCardNum());
			resultMap.put("bankName", bankCardDto.getBankName());
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(CorsFilter.threadLocalUUID.get() + "bankCradOcr 银行卡识别失败" , e);
			return FintechResult.getResult(ErrorCode.FAIL, "银行卡识别失败", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "银行卡识别成功", resultMap);
	}

	@ResponseBody
	@RequestMapping(value = "/upload/contract")
	public FintechResult uploadContract(MultipartFile file ,HttpServletRequest request,@RequestHeader String accessToken, @RequestHeader String idFintechUmUser) {
		User user = UserUtils.getUser(accessToken, idFintechUmUser);
		if (user == null) {
			return FintechResult.getFailResult(ReturnCode.tokenInvalid.getErrorCode(), "登陆超时");
		}
		Map<String, Object> resultMap = new HashMap<String,Object>();
		try {
			 MarvelsLogUtil.getInstance().info(CorsFilter.threadLocalUUID.get() + "------------------------上传 -------  file = " + file);
			// 限制文件的类型，文件的大小 TODO
			String prefix = FileUtils.getPathPrefix();
			String uuid = UUID.randomUUID().toString();
			String nfsFileSystem = FileUtils.getValueByPropertiesKey("nfs.file.system"); // 服务器地址
			String path = nfsFileSystem + prefix;
			String fileName = file.getOriginalFilename();
			try {
				fileName = "contract_" + uuid + fileName.substring(fileName.lastIndexOf("."), fileName.length());
			} catch (Exception e1) {
				fileName = "contract_" + uuid + fileName + ".pdf";
			}
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// springboot 是用这种方式会存在上传问题
			//file.transferTo(targetFile);
			String filePath = path + File.separator + fileName;
			MarvelsLogUtil.getInstance().info("上传路径：" + filePath);
			File tempFile = new File(filePath);
			org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
			String contractFilePath = nfsFileSystem + prefix.toString() + "/" + fileName;

			//1 验证是否实名认证
			RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(user.getId());
			if (null == realNameAuthentication) {
				return FintechResult.getResult(ErrorCode.NO_VERIFY, "", null);
			}

			//2 获取当前贷款申请编号
			String loanId = loanInfoIDragonService.selectCustApplyingLoanId(realNameAuthentication.getIdentityCardNo());

			CmAttachment cmAttachment = new CmAttachment();
			cmAttachment.setLoanId(loanId);
			cmAttachment.setAtmtType("contract");
			cmAttachment.setFileName(fileName);
			cmAttachment.setFileLocation(contractFilePath);
			cmAttachmentIDragonService.insertMsg(cmAttachment);
			resultMap.put("path", contractFilePath);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error(CorsFilter.threadLocalUUID.get() + "------------------------上传 -------  file = " + file, e);
			return FintechResult.getResult(ErrorCode.FAIL, "上传失败", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", resultMap);
	}

}
